<?php
class module_video extends module {
	
	function show() {
		if ($this->format == "page") {
			if (request::get("id")) {
				// request by ?id=VIDID
				document::getInstance()->setRedirect("#" . request::get("id"));
			} else {
				// request by ?VIDID
				$request = request::get("*");
				unset($request["module"]);
				$keys = array_keys($request);
				if ($keys) {
					document::getInstance()->setRedirect("#" . $keys[0]);
				}
			}
			return false;
		}
		// json request
		$this->attach("video", video::create(request::get("id"), true, true)->getAll(true));
		$this->output();
	}
	
	function runMusicBrainzCue() {
		if ($this->format == 'debug') {
			$cue = unserialize(request::get("cue"));
		} else {
			$cue = unserialize(request::post("cue"));
		}		
		musicbrainz::runCue($cue, $this->format);
	}
		
	function recordPlayStat() {
		$video_id = request::get("video_id");
		$userAuthRequest = new request(array("module" => "user", "action" => "getUid"));
		$user_id = module::load($userAuthRequest);
		if ($user_id === false) {
			$user_id = null;
		}
		$playstat = new playstat();
		$values = array(
			"video_id" => $video_id,			
			"user_id" => $user_id,
			"ip" => $_SERVER["REMOTE_ADDR"],
			"time" => date("Y-m-d G:i:s")
		);
		$result = $playstat->insert($values);
		$this->attach("status", $result ? 1 : 0);
		$this->output();
	}
	
	function recent() {
		if ($this->format == "json" || $this->format == "debug") {
			return $this->recent_json();
		}		
		$this->output();
	}
	
	function recentThumbs() {
		$this->output();
	}
	
	function recent_json() {
		$count = (int) request::get("count");
		$playstat = new playstat();
		// http://forums.mysql.com/read.php?20,134952,134981#msg-134981
		$results = $playstat->sql("
			SELECT t1.* 
			FROM playstat t1
			LEFT JOIN playstat t2 ON t1.video_id = t2.video_id
			AND t1.time < t2.time
			WHERE t2.video_id IS NULL 
			ORDER BY t1.time DESC 
			LIMIT $count
		");
		$results = array_reverse($results);
		$videos = new video_collection();
		foreach($results as $video) {
			$videos->addItem(new video($video->video_id));
		}
		$this->attach("videos", $videos->getDataArray(true));
		$this->output();
	}
	
	public function addFav() {
		$video_id = request::post("video_id");
		$userAuthRequest = new request(array("module" => "user", "action" => "getUid"));
		$user_id = module::load($userAuthRequest);
		if ($user_id === false) {
			$this->attach("status", 0);
			$this->output();
			return;
		}
		$fav = new fav();
		if ($fav->hasFav($user_id, $video_id)) {
			$this->attach("status", 'duplicate');
			$this->output();
			return;
		}
		$values = array(
			"video_id" => $video_id,			
			"user_id" => $user_id,
			"time" => date("Y-m-d G:i:s")
		);
		$result = $fav->insert($values);
		$this->attach("status", $result ? true : false);
		$this->output();
	}
}
?>